﻿using System.Diagnostics;

namespace OpenPms.Models;

public class ActionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    public ActionMiddleware(RequestDelegate next, ILoggerFactory lf)
    {
        _next = next;
        _logger = lf.CreateLogger("中间件");
    }

    public async Task InvokeAsync(HttpContext context)
    {
        Stopwatch sw = Stopwatch.StartNew();
        if (context.Request.Method != "GET")
        {
            if (context.Request.HasFormContentType)
                _logger.LogInformation($"{context.User.Identity?.Name}({context.User.GetExtId()})：{context.Request.Method} {context.Request.Path}\r\nForm:{string.Join("\r\n", context.Request.Form.Select(ii => ii.Key + ": " + ii.Value))}");
            else
            {
                context.Request.EnableBuffering();
                var streamReader = new StreamReader(context.Request.Body);
                var bodyStr = await streamReader.ReadToEndAsync();
                context.Request.Body.Position = 0;
                _logger.LogInformation($"{context.User.Identity?.Name}({context.User.GetExtId()})：{context.Request.Method} {context.Request.Path}\r\nBody:{bodyStr}");
            }
        }
        await _next(context);
        sw.Stop();
        if (sw.ElapsedMilliseconds > 1000)
            _logger.LogWarning($"{context.Request.Path}，耗时：{sw.ElapsedMilliseconds} ms");
    }
}

 